package vt.ece4564.phonetracker;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Environment;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class PhoneFinderService extends Service {
	private GPSMonitor m_GPSMonitor;
	private String m_SecretMessage;
	
	private SMSReceiver m_Receiver;
	private IntentFilter m_IntentFilter;

	public PhoneFinderService()
	{
		Log.d("Service", "Constructor");
	}
	
	@Override
	public void onCreate()
	{
		Log.d("Service", "onCreate");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) 
	{
		Log.d("Service", "onStartCommand");
		
		m_SecretMessage = intent.getStringExtra("Secret Phrase");
		
		SharedPreferences sp = getSharedPreferences("PhoneTrackerPrefsFile", 0);
		String ruleString = sp.getString("allrules", "dne");
		String alertPhone = sp.getString("alertphone", "dne");
		m_SecretMessage = sp.getString("secretphrase", "dne");
		
		m_GPSMonitor = new GPSMonitor("GPS Monitor", this, ruleString, alertPhone);
		m_GPSMonitor.start();
		
		Message msg = Message.obtain();
		msg.obj = "Hello";
		
		
		m_Receiver = new SMSReceiver(m_SecretMessage, m_GPSMonitor);
		m_IntentFilter = new IntentFilter();
        m_IntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
		registerReceiver(m_Receiver, m_IntentFilter);
		
		Log.d("Service", "Threads started and running.");
		return Service.START_STICKY;
	}
	
	@Override
	public void onDestroy() 
	{
		Log.d("Service", "onDestroy");
		
		m_GPSMonitor.run_State = false;
		Message msg = Message.obtain();
		msg.obj = "TERMINATE";
		m_GPSMonitor.Handler.sendMessage(msg);
		
		//while (!m_GPSMonitor.isFinished);
		
		Log.d("Service", "Threads have been closed. Terminating service.");
    }

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	

}
